#include "satellitetrack.h"
#include "ui_satellitetrack.h"

#undef slots // avoid conflicts with qt macro definition
#include <Python.h>
#define slots Q_SLOTS

#include <QDateTime>
#include <QFile>

#include "common/data.h"
#include "common/database.h"
#include "common/tool.h"

SatelliteTrack::SatelliteTrack(QWidget* parent)
    : QWidget(parent)
    , ui(new Ui::SatelliteTrack)
    , m_timer(new QTimer(this))
{
    ui->setupUi(this);

    Database::loadStations();
    for (int i = 0; i < Data::stations.size(); ++i)
    {
        ui->comboStation->addItem(Data::stations[i].name, i);
    }

    Py_Initialize();
    PyRun_SimpleString("import skyfield.api as sf");
    PyRun_SimpleString("satellites = sf.load.tle_file('../res/tle.txt')");
    PyRun_SimpleString("by_name = {sat.name: sat for sat in satellites}");
    PyRun_SimpleString("with open('./sat_name.txt', 'w') as f: f.write(', '.join([sat.name for sat in satellites]))");

    QFile file("sat_name.txt");
    file.open(QIODevice::ReadOnly);
    QStringList sat_name = QString(file.readLine()).split(", ");
    file.close();
    ui->comboSatellite->addItems(sat_name);

    connect(ui->btnStart, &QPushButton::clicked, this, [&]()
            {
        m_timer->start(1000);
        displayPosition();
        ui->btnStart->setEnabled(false);
        ui->btnStop->setEnabled(true);
        ui->comboStation->setEnabled(false);
        ui->comboSatellite->setEnabled(false); });
    connect(ui->btnStop, &QPushButton::clicked, this, [&]()
            {
        m_timer->stop();
        ui->btnStart->setEnabled(true);
        ui->btnStop->setEnabled(false);
        ui->comboStation->setEnabled(true);
        ui->comboSatellite->setEnabled(true); });
    connect(ui->btnClear, &QPushButton::clicked, ui->plainText, &QPlainTextEdit::clear);
    connect(m_timer, &QTimer::timeout, this, &SatelliteTrack::displayPosition);
}

SatelliteTrack::~SatelliteTrack()
{
    Py_Finalize();
    delete ui;
}

void SatelliteTrack::displayPosition()
{
    int stationId = ui->comboStation->currentData().toInt();
    QString satelliteName = ui->comboSatellite->currentText();

    PyRun_SimpleString(QString("satellite = by_name['%1']").arg(satelliteName).toLatin1());
    PyRun_SimpleString("t = sf.load.timescale().now()");
    PyRun_SimpleString("lla = sf.wgs84.geographic_position_of(satellite.at(t))");
    PyRun_SimpleString(QString("station = sf.wgs84.latlon(%1, %2)").arg(Data::stations[stationId].latitude).arg(Data::stations[stationId].longitude).toLatin1());
    PyRun_SimpleString("E, A, D = (satellite - station).at(t).altaz()");
    PyRun_SimpleString("with open('./geo_info.txt', 'w') as f: f.write(f'{lla.longitude.degrees}, {lla.latitude.degrees}, {lla.elevation.km}, {A.degrees}, {E.degrees}, {D.km}')");

    QFile file("geo_info.txt");
    file.open(QIODevice::ReadOnly);
    QStringList geo_info = QString(file.readLine()).split(", ");
    file.close();

    ui->plainText->appendPlainText(QString("【当前时刻】%1").arg(QDateTime::currentDateTime().toString(Tool::DATETIME_FORMAT)));
    ui->plainText->appendPlainText(QString("【站点】名称：%1，经度：%2，纬度：%3").arg(Data::stations[stationId].name).arg(Data::stations[stationId].longitude).arg(Data::stations[stationId].latitude));
    ui->plainText->appendPlainText(QString("【卫星】名称：%1，经度：%2，纬度：%3，高度：%4 km").arg(satelliteName, geo_info[0], geo_info[1], geo_info[2]));
    ui->plainText->appendPlainText(QString("【站点对卫星】方位角：%1，俯仰角：%2，距离：%3 km").arg(geo_info[3], geo_info[4], geo_info[5]));
    ui->plainText->appendPlainText("\n");
}
